package com.gdcp.controller.backend;

import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.*;
import com.gdcp.util.RequestUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/commentManager")
public class CommentController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    CommentService commentService;
    @Autowired
    CommonCode commonCode;
    @Autowired
    ProductService productService;
    @Autowired
    UserService userService;
    @Autowired
    OrderItemService orderItemService;

    //一开始查询出来的评论列表，它根据权限划分查询
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){

        Map<String,Object> model=commonCode.getList(pageSize, pageNumber, sortName, sortOrder);

        //通过
        User user= (User) RequestHolder.getSession("user");
        Integer shop_id=user.getShop_id();
        model.put("shop_id",shop_id);
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                return commentService.findAll(model);
            }
        }

        return commentService.findPageBreakByCondition(model, shop_id);
    }

    //删除，注意：没有使用权限限制
    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }

        return commentService.removeByPrimaryKey(ids);
    }

    //添加评论
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @RolesAllowed({"ROLE_ADMIN"})
    public Map<String,Object> add(@RequestParam("parent_id")  String fp_parentId, @RequestParam("product_id")  String fp_productId, @RequestParam("content") String fp_content,
                                  @RequestParam("user_id") String fp_userId, @RequestParam("support") String fp_support, @RequestParam("oppose") String fp_oppose,
                                  @RequestParam("orderitem_id") String fp_orderItemId, @RequestParam("user_name") String fp_userName){
        if (fp_parentId==null||fp_parentId.equals("")){
            return responseModel.setModel(false,"新增失败,你的父类id能为空");
        }
        if (fp_productId==null||fp_productId.equals("")){
            return responseModel.setModel(false,"新增失败,你的商品id不能为空");
        }
        if (fp_userId==null||fp_userId.equals("")){
            return responseModel.setModel(false,"新增失败,你的用户id能为空");
        }
        if (fp_support==null||fp_support.equals("")){
            return responseModel.setModel(false,"新增失败,你的点赞不能为空");
        }
        if (fp_oppose==null||fp_oppose.equals("")){
            return responseModel.setModel(false,"新增失败,你的踩不能为空");
        }
        if (fp_orderItemId==null||fp_orderItemId.equals("")){
            return responseModel.setModel(false,"新增失败,你的订单子项id能为空");
        }

        Integer parentId= Integer.valueOf(fp_parentId);
        Integer productId= Integer.valueOf(fp_productId);
        Integer userId= Integer.valueOf(fp_userId);
        Integer support= Integer.valueOf(fp_support);
        Integer oppose= Integer.valueOf(fp_oppose);
        Integer orderItemId= Integer.valueOf(fp_orderItemId);


        Product product=productService.getInformation(productId);
        if (product==null){
            return responseModel.setModel(false,"商品id不存在");
        }
        User user=userService.getInformation(userId);
        if (user==null){
            return responseModel.setModel(false,"用户id不存在");
        }
        OrderItem orderItem=orderItemService.getInformation(orderItemId);
        if (orderItem==null){
            return responseModel.setModel(false,"订单id不存在");
        }

        Comment comment=new Comment();
        comment.setParent_id(parentId);
        comment.setProduct_id(productId);
        comment.setUser_id(userId);
        comment.setUser_name(fp_userName);
        comment.setContent(fp_content);
        comment.setSupport(support);
        comment.setOppose(oppose);
        comment.setOrderitem_id(orderItemId);

        return commentService.insert(comment);
    }

    //评论编辑，情景复杂
    //情景一：店员或店长，回复评论或者编辑自己写的评论
    //实现方式：
    //1、使用权限区分
    //2、如果是
    //情景二：管理员，编辑评论，真的是编辑。(希望)
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(@RequestParam("id") String fp_id, @RequestParam("parent_id")  String fp_parentId, @RequestParam("product_id")  String fp_productId,
                                   @RequestParam("reply")  String fp_reply, @RequestParam("content") String fp_content,
                                   @RequestParam(value="user_id",required = false) String fp_userId, @RequestParam(value="support",required = false) String fp_support,
                                   @RequestParam(value="oppose",required = false) String fp_oppose, @RequestParam(value="orderitem_id",required = false) String fp_orderItemId,
                                   @RequestParam(value="user_name",required = false) String fp_userName){
        if (fp_id==null||fp_id.equals("")){
            return responseModel.setModel(false,"id不能为空");
        }

        if (fp_parentId==null||fp_parentId.equals("")){
            return responseModel.setModel(false,"parent_id不能为空");
        }

        if (fp_productId==null||fp_productId.equals("")){
            return responseModel.setModel(false,"新增失败,你的商品id不能为空");
        }


        Comment comment=new Comment();
        Integer productId= Integer.valueOf(fp_productId);
        comment.setProduct_id(productId);

        //不是编辑，而是新增，父类为id，reply为回复
        Integer id= Integer.valueOf(fp_id);
        Integer parentId= Integer.valueOf(fp_parentId);
        User user= (User) RequestHolder.getSession("user");

        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                if (fp_userId==null||fp_userId.equals("")){
                    return responseModel.setModel(false,"你的用户id能为空");
                }
                if (fp_support==null||fp_support.equals("")){
                    return responseModel.setModel(false,"你的点赞不能为空");
                }
                if (fp_oppose==null||fp_oppose.equals("")){
                    return responseModel.setModel(false,"你的踩不能为空");
                }
                if (fp_orderItemId==null||fp_orderItemId.equals("")){
                    return responseModel.setModel(false,"你的订单子项id能为空");
                }

                comment.setProduct_id(productId);
                Product product=productService.getInformation(productId);
                if (product==null){
                    return responseModel.setModel(false,"商品id为"+comment.getProduct_id()+"，它不存在");
                }
                comment.setShop_id(product.getShop_id());

                Integer user_id= Integer.valueOf(fp_userId);
                comment.setUser_id(user_id);
                User user1=userService.getInformation(comment.getUser_id());
                if (user1==null){
                    return responseModel.setModel(false,"用户id为"+comment.getUser_id()+"，它不存在");
                }

                Integer support= Integer.valueOf(fp_support);
                comment.setSupport(support);

                Integer oppose = Integer.valueOf(fp_oppose);
                comment.setOppose(oppose);
                comment.setParent_id(parentId);
                comment.setUser_name(fp_userName);
                if (parentId==0){
                    comment.setId(id);
                    comment.setContent(fp_content);
                    return commentService.updateInformation(comment);
                }
            }
        }

        //如果不为0，那么就是第二条回复，编辑，可以编辑里面的内容。。。
        if (parentId!=0){
            comment.setId(id);
            comment.setContent(fp_content);
            return commentService.updateInformation(comment);
        }

        //如果id为0，那么就是第一条，插入或者编辑，
        //存在，那么就是编辑。
        Comment comment1=commentService.getInformationByParentId(id);
        if (comment1==null){
            Product product=productService.getInformation(comment.getProduct_id());
            if (product==null){
                return responseModel.setModel(false,"商品id为"+comment.getProduct_id()+"，它不存在");
            }

            comment.setShop_id(product.getShop_id());

            //判断这个商品的shopId是否存在
            /*if (comment.getShop_id() == null) {
                comment.setShop_id(user.getShop_id());
            }*/
            comment.setUser_name(fp_userName);
            comment.setUser_id(user.getId());
            comment.setParent_id(id);
            comment.setContent(fp_reply);
            return commentService.insert(comment);
        }

        //如果它不为null，那么它就编辑
        //Comment comment2=commentService.queryInfoByParentId(comment1.getId());
        comment.setId(comment1.getId());
        //如果不是新创建，那么就是修改（这是店长情况下）
        comment.setContent(fp_reply);
        return commentService.updateInformation(comment);
    }


    @RequestMapping(value = "/editByOrderItem",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> editByOrderItem(@RequestParam("id") String fp_id, @RequestParam(value="parent_id",required = false)  String fp_parentId, @RequestParam(value="product_id",required = false)  String fp_productId,
                                              @RequestParam("reply")  String fp_reply, @RequestParam("content") String fp_content, @RequestParam(value="user_name",required = false) String fp_userName){
        if (fp_id==null||fp_id.equals("")){
            return responseModel.setModel(false,"id不能为空");
        }

        if (fp_parentId==null||fp_parentId.equals("")){
            return responseModel.setModel(false,"parent_id不能为空");
        }

        if (fp_productId==null||fp_productId.equals("")){
            return responseModel.setModel(false,"你的商品id不能为空");
        }


        Comment comment=new Comment();
        Integer productId= Integer.valueOf(fp_productId);
        comment.setProduct_id(productId);

        //不是编辑，而是新增，父类为id，reply为回复
        Integer id= Integer.valueOf(fp_id);
        Integer parentId= Integer.valueOf(fp_parentId);

        //如果不为0，那么就是第二条回复，编辑
        if (parentId!=0){
            comment.setId(id);
            comment.setContent(fp_content);
            return commentService.updateInformation(comment);
        }

        //如果id为0，那么就是第一条，插入或者编辑，
        //存在，那么就是编辑。
        Comment comment1=commentService.getInformationByParentId(id);
        if (comment1==null){
            Product product=productService.getInformation(comment.getProduct_id());
            if (product==null){
                return responseModel.setModel(false,"商品id为"+comment.getProduct_id()+"，它不存在");
            }

            comment.setShop_id(product.getShop_id());

            //判断这个商品的shopId是否存在
            /*if (comment.getShop_id() == null) {
                comment.setShop_id(user.getShop_id());
            }*/
            User user= (User) RequestHolder.getSession("user");
            comment.setUser_name(fp_userName);
            comment.setUser_id(user.getId());
            comment.setParent_id(id);
            comment.setContent(fp_reply);
            return commentService.insert(comment);
        }

        //如果它不为null，那么它就编辑
        //Comment comment2=commentService.queryInfoByParentId(comment1.getId());
        comment.setId(comment1.getId());
        //如果不是新创建，那么就是修改（这是店长情况下）
        comment.setContent(fp_reply);
        return commentService.updateInformation(comment);
    }

    @PostMapping("/get/{id}")
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Comment comment=commentService.getInformation(id);
        if (comment!=null){
            return responseModel.setModel(true,comment);
        }

        return responseModel.setModel(false,"获取失败");
    }

    @PostMapping("/getByOrderItem/{id}")
    @ResponseBody
    public Map<String,Object> getByOrderItem(@PathVariable Integer id){
        Comment comment=commentService.getInformationByOrderItemId(id);
        if (comment!=null){
            return responseModel.setModel(true,comment);
        }

        return responseModel.setModel(false,"获取失败");
    }

    @PostMapping("/search")
    @ResponseBody
    public Map<String,Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("user_id", jsonOne.getString("user_id"));
            param.put("parent_id", jsonOne.getString("parent_id"));
            param.put("product_id", jsonOne.getString("product_id"));
        }

        //通过
        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                return commentService.searchInformation(param);
            }
        }

        param.put("shop_id",user.getShop_id());
        if (user.getShop_id()==0){
            return responseModel.setModel(false,"信息错误");
        }
        return commentService.searchInformationByShopId(param,user.getShop_id());
    }
}
